package dilmaj.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import dilmaj.client.AddAreasPanel.CloseHandler;
import dilmaj.shared.TermVO;

public class SuggestionPanel extends PopupPanel {
	TermVO termVO;
	TermServiceAsync termSvc = GWT.create(TermService.class);
	VerticalPanel mainPanel=new VerticalPanel();
	TextBox suggestionBox=new TextBox();
	Button closeButton=new Button("Close");
	TestGWT owner;

	public SuggestionPanel(TestGWT owner, boolean isEditable, TermVO termVO) {
		this.owner=owner;
		this.termVO=termVO;
		CloseHandler closeHandler=new CloseHandler(this);
		closeButton.addClickHandler(closeHandler);
		mainPanel.add(suggestionBox);
		mainPanel.add(closeButton);

		suggestionBox.setEnabled(isEditable);
		suggestionBox.setText(termVO.getSuggestion());
				
		add(mainPanel);
	}
	
	class CloseHandler implements ClickHandler {
		private SuggestionPanel owner;
		
		public CloseHandler(SuggestionPanel owner) {
			this.owner=owner;
		}
		
		public void onClick(ClickEvent event) {
			termVO.setSuggestion(suggestionBox.getText());

		    if (termSvc == null) {
			      termSvc = GWT.create(TermService.class);
		    }
		    termSvc.update(termVO, updateCallback);
		    
			owner.hide();
		}
	}
	
	AsyncCallback<TermVO> updateCallback = new AsyncCallback<TermVO>() {
		public void onFailure(Throwable caught) {
			        // TODO: Do something with errors.
		}
	
		public void onSuccess(TermVO result) {
			owner.updateTermRow(result, true);
		}
	};
}
